const localStoragePlugin = (store) => {
  // 当 store 初始化后调用
  const localState = JSON.parse(localStorage.getItem('vuexState') || '{}')
  const newState = { ...store.state }
  newState.local = localState
  store.replaceState(newState)
  let timer = null
  store.subscribe((mutation, state) => {
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
    if (!mutation.type.startsWith('local/')) return
    const watchedDatas = {}
    // 设置了一个local的modules,只有这个模块下的state才需要被同步
    console.log('state', state)
    Object.keys(state.local || {}).forEach((key) => {
      watchedDatas[key] = state.local[key]
    })
    clearTimeout(timer)
    timer = setTimeout(() => {
      localStorage.setItem('vuexState', JSON.stringify(watchedDatas))
    }, 300)
  })
}
export default localStoragePlugin
